#include <iostream>
#include <cstdlib>
#include <unistd.h> 

//using namespace std;

bool GetQueryString(std::string &query_string)
{
  bool result = false;
  //2 cerr 只有2只有2没有被重定向
  std::string method = getenv("METHOD"); 
  //std::cerr<<"####### Debug Method: " << getenv("METHOD")<<std::endl;
  //std::string query_string;
  //std::cerr << "......................................." << std::endl;
  if(method == "GET")
  {
    query_string = getenv("QUERY_STRING");
    //std::cerr << "GET DEBUG QUERY_STRING: " << query_string << std::endl;
    result = true;
  }
  else if("POST" == method)
  {
    //CGI如何知道需要从标准输入读取多少字节呢？
    //std::cerr << "Content-Length: " << getenv("CONTENT_LENGTH") << std::endl;
    int content_length = atoi(getenv("CONTENT_LENGTH"));
    char c = 0;
    while(content_length)
    {
      read(0, &c, 1);
      query_string.push_back(c);
      content_length--;
    }
    result = true; 
    //std::cerr << "POST  DEBUG QUERY_STRING: " << query_string << std::endl;
  }
  else 
  {
    result = false; 
  }
  return result; 
  //std::cerr << "+++++++++++++++++++++++++++++++++++++" << std::endl;
}

void CutString(std::string &in, const std::string &seq, std::string &out1, std::string &out2)
{
  auto pos = in.find(seq);
  if(std::string::npos != pos)
  {
    out1 = in.substr(0, pos);
    out2 = in.substr(pos+seq.size());
  }
}
int main()
{
  std::string query_string; 
  GetQueryString(query_string);
  // a=200&b=300 字符串处理
 
  std::string str1;
  std::string str2;
  CutString(query_string, "&", str1, str2);


  std::string name1;
  std::string value1;
  CutString(str1, "=", name1, value1);


  std::string name2;
  std::string value2;
  CutString(str2, "=", name2, value2);

  //显示给 1 被写入管道中
  std::cout << name1 << " : " << value1 << std::endl;
  std::cout << name2 << " : " << value2 << std::endl;

  //显示给 2
  std::cerr << name1 << " : " << value1 << std::endl;
  std::cerr << name2 << " : " << value2 << std::endl;
  return 0;
}
